﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathLib {
    public class Gauss {

        private const double g1 = 2.515517;
        private const double g2 = 0.802853;
        private const double g3 = 0.01328;
        private const double l1 = 0.01328;
        private const double l2 = 0.189269;
        private const double l3 = 0.001308;

        private static Random rnd = new Random();

        public double Next(double a, double sigma) {
            double r = rnd.NextDouble();
            double x = r <= 0.5 ? -G(1 - r) : G(r);
            return a + sigma * x;
        }
        
        private double Theta(double z) {
            return Math.Sqrt(-2.0 * Math.Log(z));
        }

        private double G(double z) {
            double th = Theta(z);
            return -th + (g1 + g2 * th + g3 * th * th) / (1 + l1 * th + l2 * th * th + l3 * th * th * th);
        }
        
    }
}